﻿using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using Ninject.Modules;
using Spotted.WebApi.Extensions;

namespace Spotted.WebApi.Core
{
    public class WebApiNinjectModule : NinjectModule
    {
        private readonly Assembly _targetAssembly;

        public WebApiNinjectModule(Assembly targetAssembly)
        {
            _targetAssembly = targetAssembly;
        }

        #region Overrides of NinjectModule

        /// <summary>
        /// Loads the module into the kernel.
        /// </summary>
        public override void Load()
        {
            var applicableTypes = _targetAssembly.GetTypes()
                .Where(t => t.GetInterfaces().Contains(typeof (IHttpController)))
                .ToList();

            applicableTypes.ForEach(hc =>
                    {
                        if (!string.IsNullOrEmpty(hc.Name))
                        {
                            var controllerName = hc.Name.AsControllerName();
                            Bind<IHttpController>().To(hc).Named(controllerName);
                        }
                    });
        }

        #endregion
    }
}